﻿#include "QNetworkAdapterInfoProvider.h"
#include <QDebug>
#include <QMap>
#include <memory>

#ifdef Q_OS_WIN
#include <windows.h>
#include <iphlpapi.h>
#endif

QVector<QNetworkAdapterInfoProvider::NetworkAdapterDetails>
QNetworkAdapterInfoProvider::getNetworkAdapters() const {
#ifdef Q_OS_WIN
    return getNetworkAdaptersWindows();
#else
    return getNetworkAdaptersLinux();
#endif
}

#ifdef Q_OS_WIN
QVector<QNetworkAdapterInfoProvider::NetworkAdapterDetails>
QNetworkAdapterInfoProvider::getNetworkAdaptersWindows() const {
    QVector<NetworkAdapterDetails> adapters;
    QMap<int, NetworkAdapterDetails> tempAdapters;

    // 1. 通过Qt获取基础信息
    const QList<QNetworkInterface> qtInterfaces = QNetworkInterface::allInterfaces();
    for (const QNetworkInterface& iface : qtInterfaces) {

        // 关键：跳过环回接口（IsLoopBack 标志）
        if (iface.flags () & QNetworkInterface::IsLoopBack) {
        continue; // 直接跳过回环接口
        }

        NetworkAdapterDetails details;
        details.index = iface.index();
        details.name = iface.name();
        details.description = iface.humanReadableName();
        details.macAddress = iface.hardwareAddress();
        details.mtu = iface.maximumTransmissionUnit();
        details.isAdminUp = iface.flags() & QNetworkInterface::IsUp;
        details.operationalStatus = "Unknown"; // 初始化为未知
        details.type = 0;
        details.speed = 0;

        tempAdapters[details.index] = details;
    }

    // 2. 通过Windows API补充详细信息
    DWORD bufferSize = 0;
    if (GetIfTable(nullptr, &bufferSize, FALSE) != ERROR_INSUFFICIENT_BUFFER) {
        qWarning() << "获取接口表缓冲区大小失败";
        return adapters;
    }

    std::unique_ptr<BYTE[]> buffer(new BYTE[bufferSize + 1024]);
    PMIB_IFTABLE pIfTable = reinterpret_cast<PMIB_IFTABLE>(buffer.get());

    if (GetIfTable(pIfTable, &bufferSize, FALSE) != NO_ERROR) {
        qWarning() << "获取接口表数据失败";
        return adapters;
    }

    // 3. 解析接口信息并匹配Qt接口
    for (DWORD i = 0; i < pIfTable->dwNumEntries; ++i) {
        const MIB_IFROW& ifRow = pIfTable->table[i];
        const int index = static_cast<int>(ifRow.dwIndex);

        if (tempAdapters.contains(index)) {
            NetworkAdapterDetails& details = tempAdapters[index];

            // 补充接口类型
            details.type = ifRow.dwType;

            // 补充操作状态（使用提供的INTERNAL_IF_OPER_STATUS枚举）
            switch (static_cast<INTERNAL_IF_OPER_STATUS>(ifRow.dwOperStatus)) {
                case IF_OPER_STATUS_NON_OPERATIONAL:
                    details.operationalStatus = "Non-operational"; // 非运行状态
                    break;
                case IF_OPER_STATUS_UNREACHABLE:
                    details.operationalStatus = "Unreachable";     // 不可达
                    break;
                case IF_OPER_STATUS_DISCONNECTED:
                    details.operationalStatus = "Disconnected";    // 已断开
                    break;
                case IF_OPER_STATUS_CONNECTING:
                    details.operationalStatus = "Connecting";      // 连接中
                    break;
                case IF_OPER_STATUS_CONNECTED:
                    details.operationalStatus = "Connected";       // 已连接
                    break;
                case IF_OPER_STATUS_OPERATIONAL:
                    details.operationalStatus = "Operational";     // 运行中
                    break;
                default:
                    details.operationalStatus = "Unknown";
            }

            // 补充网卡速度（bps）
            details.speed = static_cast<quint64>(ifRow.dwSpeed);
        }
    }

    // 4. 转换为结果列表
    for (const auto& details : tempAdapters) {
        adapters.append(details);
    }
    return adapters;
}
#else
// Linux平台实现（保持不变）
QVector<QNetworkAdapterInfoProvider::NetworkAdapterDetails>
QNetworkAdapterInfoProvider::getNetworkAdaptersLinux() const {
    QVector<NetworkAdapterDetails> adapters;
    QMap<QString, NetworkAdapterDetails> tempAdapters;

    // 通过Qt获取基础信息
    const QList<QNetworkInterface> qtInterfaces = QNetworkInterface::allInterfaces();
    for (const QNetworkInterface& iface : qtInterfaces) {
        NetworkAdapterDetails details;
        details.index = iface.index();
        details.name = iface.name();
        details.description = iface.humanReadableName();
        details.macAddress = iface.hardwareAddress();
        details.mtu = iface.maximumTransmissionUnit();
        details.isAdminUp = iface.flags() & QNetworkInterface::IsUp;

        // 操作状态（简化判断）
        details.operationalStatus = iface.flags() & QNetworkInterface::IsUp ? "Connected" : "Disconnected";

        // 初始化其他信息
        details.type = 0;
        details.speed = 0;

        tempAdapters[details.name] = details;
    }

    // 补充速度和类型信息
    for (auto& entry : tempAdapters.toStdMap()) {
        NetworkAdapterDetails& details = entry.second;

        // 读取速度（Mbps转换为bps）
        const QString speedPath = QString("/sys/class/net/%1/speed").arg(details.name);
        QFile speedFile(speedPath);
        if (speedFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&speedFile);
            QString speedStr = in.readLine().trimmed();
            bool ok = false;
            quint64 speedMbps = speedStr.toULongLong(&ok);
            if (ok) {
                details.speed = speedMbps * 1000000;
            }
            speedFile.close();
        }

        // 判断接口类型
        if (details.name.contains("eth", Qt::CaseInsensitive) ||
            details.name.contains("enp", Qt::CaseInsensitive)) {
            details.type = 6; // 以太网
        } else if (details.name.contains("wlan", Qt::CaseInsensitive) ||
                   details.name.contains("wlp", Qt::CaseInsensitive)) {
            details.type = 71; // 无线
        } else if (details.name.contains("lo", Qt::CaseInsensitive)) {
            details.type = 24; // 环回
        } else {
            details.type = 1; // 其他
        }

        adapters.append(details);
    }

    return adapters;
}
#endif
